from django.shortcuts import render

# Create your views here.

from rest_framework.views import APIView
from rest_framework.response import Response
from .models import *
from .serializer import *
from rest_framework.viewsets import ModelViewSet
import random,datetime
from utils.celery_task.task import send_message
from rest_framework import viewsets
import json,random,datetime
# 导入封装redis
from utils.redsi_con import redis_conn
# 加密，检查密码
from django.contrib.auth.hashers import make_password,check_password
# 导入生成token
from utils.token_utils import login_token
# 导入
from utils.Myalipay import MyAlipay

# 用户视图
class UserView(viewsets.ViewSet):
    # 发送短信验证码
    def sms_code(self,request,mobile):
        try:
            sms_code = '%06d' % random.randint(0, 1000000)
            expire = 10
            # 提交异步任务celery 队列
            send_message.delay(sms_code, mobile, expire)
            redis_conn().set("sms_%s" % mobile, sms_code, ex=300)
            return Response({"code": 200, "message": "短信验证码已发送！"})
        except Exception as e:
            print("错误", e)
            return Response({"code": 500, "message": "服务器错误！"})

    #注册
    def register_user(self,request):
        try:
            nickname = request.data.get("nickname")
            password = request.data.get("password")
            mobile = request.data.get("mobile")
            sms_code = request.data.get("sms_code")
            print("数据", nickname, password, mobile, sms_code)
            user = UserModel.objects.filter(mobile=mobile, is_delete=False).first()
            if user:
                return Response({"code": 204, "message": "手机号已注册！"})
            # code = redis_conn().get("sms_%s" % mobile)
            # if not code:
            #     return Response({"code": 204, "message": "验证码已过期！"})
            # code = code.decode()
            # if sms_code.lower() != code.lower():
            #     return Response({"code": 400, "message": "验证码错误！"})
            hash_pwd = make_password(password)
            UserModel.objects.create(nickname=nickname, password=hash_pwd, mobile=mobile,)
            return Response({"code": 200, "message": "注册成功！"})
        except Exception as e:
            print("注册失败",e)
            return Response({"code":500,"message":"服务器错误"})

    #登录
    def login(self,request):
        try:
            nickname = request.data.get("nickname")
            password = request.data.get("password")
            user = UserModel.objects.filter(nickname=nickname ,is_delete=False).first()
            if not user :
                return Response({"code":204,"message":"用户不存在"})
            if check_password(password,user.password):
                user.last_login = datetime.datetime.now()# 更新登录时间
                user.save()
                # 有权限登录站点
                payloads = {
                    "user_id": user.id,
                    "nickname": user.nickname,
                }
                token, refresh_token = login_token(payloads)
                ser = UserSer(user)
                return Response({
                    "code": 200,
                    "msg": "登录成功！",
                    "token": token,
                    "refresh_token": refresh_token,
                    "user": ser.data,
                })
            return Response({"code": 204, "message": "用户名或密码错误！"})
        except Exception as e:
            print("错误",e)
            return Response({"code": 500, "message": "服务器错误！"})

    #获取用户信息
    def user_dict(self, request):
        try:
            user_id = request.session.get("user_id")

            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({"code": 204, "message": "用户不存在！"})
            ser = UserSer(user)
            return Response({"code": 200, "message": "ok！", "user_dict": ser.data})
        except Exception as e:
            print("错误", e)
            return Response({"code": 500, "message": "服务器错误！"})

    # 修改用户信息
    def up_user(self, request):
        try:
            user = request.session.get("user")
            if not user:
                return Response({"code": 402, "message": "请重新登录"})
            user_id = user.get("user_id")

            nickname = request.query_params.get("nickname")
            avatar_url = request.query_params.get("avatar_url")
            password = request.query_params.get("password")

            flag = UserModel.objects.filter(nickname=nickname, is_delete=False).exclude(id=user_id).count()
            if flag != 0:
                return Response({"code": 204, "message": "该用户名已存在！"})

            user = UserModel.objects.filter(id=user_id, is_delete=False)
            if not user:
                return Response({'code': 400, 'message': '用户不存在！'})
            if nickname:
                user.update(nickname=nickname)
            if avatar_url:
                user.update(avatar_url=avatar_url)
            if password:
                hash_pwd = make_password(password)
                user.update(password=hash_pwd)
            return Response({
                'code': 200,
                'message': '修改成功！',
            })
        except Exception as e:
            print("错误", e)
            return Response({'code': 500, 'message': '服务器错误！'})

# 修改用户
class UpUserView(ModelViewSet):
    queryset = UserModel.objects.all()
    serializer_class = UserSer
    lookup_field = "pk"
    lookup_url_kwarg = "pk"

    def update(self, request, *args, **kwargs):
        try:
            user = self.get_object()
            user.avatar_url = request.data.get('avatar_url')
            user.nickname = request.data.get('nickname')
            user.mobile = request.data.get('mobile')
            password1 = request.data.get('password')
            user.password = make_password(password1)
            user.save()
        except:
            return Response({'code': 400, 'msg': "更新用户数据报错"})
        return Response({'code': 200, 'msg': '更新用户信息成功'})

# 收货地址管理
class AddrViewSet(ModelViewSet):
    queryset = AddressModel.objects.all()
    serializer_class = AddressSer
    lookup_field = "pk"
    lookup_url_kwarg = "pk"



# 提交订单
class Order_view(viewsets.ViewSet):
    myalipay = MyAlipay()
    # 创建订单
    def now_order(self, request):
        try:
            user_id = request.session.get("user_id")
            shops_id = request.data.get("shops_id")
            goods = request.data.get("goods_list")
            pay_method = request.data.get("pay_method")
            sum = request.data.get("sum")
            total_amount = request.data.get("sum_price")
            adrs_id = request.data.get("adrs_id")
            print("》》》》查看 ",shops_id,type(goods),pay_method,sum,total_amount,adrs_id)
            pay_time = datetime.datetime.now().timestamp()
            #订单id
            # 订单id
            order_id = str(pay_time * 1000000) + str(user_id) + str(random.randint(100000, 999999))
            order = OrderModel.objects.create(user_id=user_id, shops_id=shops_id, sum=sum, total_amount=total_amount,
                                              order_id=order_id, address_id=adrs_id, pay_method=pay_method)
            print(goods)
            for i in goods:
                OrderGoodsModel.objects.create(order_id=order.id, goods_id=i["id"], sum=i["num"],
                                               sum_price=i["sum_price"])
            return_url = "http://localhost:8080/index/user_order"
            url = self.myalipay.get_pay_url(order_id, total_amount, return_url)
            return Response({"code": 200, "message": "ok！","url":url })
        except Exception as e:
            print("错误", e)
            return Response({"code": 500, "message": "服务器错误！"})

    # 校验订单是否支付成功
    def auth_check(self, request):
        try:
            order_id = request.query_params.get("out_trade_no")
            trade_no = request.query_params.get("trade_no")
            print("?????>>>>>",order_id,trade_no)
            order = OrderModel.objects.filter(order_id=order_id, is_delete=False)
            if not order:
                return Response({"code": 204, "message": "订单不存在！"})
            if not self.myalipay.check(order_id):
                return Response({"code": 204, "message": "支付失败！"})
            order.update(pay_state=2, trade_no=trade_no)
            return Response({"code": 200, "message": "支付成功！"})
        except Exception as e:
            print("错误", e)
            return Response({"code": 500, "message": "服务器错误！"})

    #查看用户订单
    def list(self, request):
        try:
            user_id = request.session.get("user_id")
            order_list = OrderModel.objects.filter(user_id=user_id,is_delete=False).all()
            ser = OrderSer(order_list,many=True)
            order_list = ser.data
            return Response({"code": 200, "message": "ok！","order_list": order_list})
        except Exception as e:
            print("错误", e)
            return Response({"code": 500, "message": "服务器错误！"})


# 获取评论
class CommonAPIView(ModelViewSet):
    queryset = CommentModel.objects.all()
    serializer_class = CommonSer
    lookup_field = "pk"
    lookup_url_kwarg = "pk"
